<?php

class FilterChain
{

  protected $filters = array();

  public function addFilter($callback, $chain = 'default')
  {
    $args = func_get_args();
    unset($args[0], $args[1]);
    
    $this->filters[$chain][] = array($callback, empty($args) ? null : $args);
    return $this;
  }

  public function executeFilter($chain = 'default', $output = null)
  {
    if (empty($this->filters[$chain])) {
      return $output;
    }

    $args = func_get_args();
    unset($args[0], $args[1]);
    $args = empty($args) ? null : $args;

    $filters = $this->filters[$chain];

    foreach ($filters as $filter) {
      $callback = $filter[0];
      $params = $filter[1];

      $params = array_merge((array)$output, (array)$params, (array)$args);
      
      $output = call_user_func_array($callback, $params);
    }

    return $output;
  }

}
